import { objectToQuery } from '@/cross/utils';
import { RuntimeOptionsConfig } from '@alilc/lowcode-types';
import axios, { AxiosRequestConfig, AxiosRequestHeaders, Method } from 'axios';

/**
 * @deprecated
 */
export function createRequestHandler(config?: Record<string, unknown>) {
  return async function (options: RuntimeOptionsConfig & { query: Record<string, string> }) {
    const { contentType, uri, query, params, method, headers = {} } = options;
    const data = contentType === 'FORM' && Object.keys(params).length > 0 ? new FormData() : params;
    params['source_client'] = 'vendor';
    if (contentType === 'FORM') {
      for (const k in params) {
        if (typeof params[k] !== 'undefined' && data?.append) {
          (data as FormData).append(k, params[k] as any);
        }
        delete params[k];
      }
    }
    delete options.contentType;
    const url =
      uri.replace('huafutong-api.keyrey.tech', 'hft-win-java.keyrey.tech') +
      (query && Object.keys(query).length > 0 ? objectToQuery(query) : '');
    const requestConfig: AxiosRequestConfig = {
      ...options,
      url,
      method: method as Method,
      data,
      headers: headers as AxiosRequestHeaders,
      ...config,
    };
    // console.log('[requestConfig] ', requestConfig);
    const response = await axios(requestConfig);
    // console.log('[response] ', response);
    return response;
  };
}
